<template>
	<view class="container flex-c">
		<view class="head flex-r">
			<view class="head-info flex-c">
				<text class="title">完善信息</text>
				<text class="info">完善个人信息，让更多人认识你吧～</text>
			</view>
			<image src="@/public/images/user/wsxx@3x.png" mode="aspectFit"></image>
		</view>
		<view class="body flex-c">
			<view class="list-item flex-r ac">
				<text class="item-title">头像</text>
				<view class="item-right flex-r ac" @tap="chooseImage">
					<image class="avatar" :src="avatarImage || user.avatar || $CHS.defaultUserAvatar" mode="aspectFill"></image>
					<uni-icons type="right" color="#999999" size="38rpx"></uni-icons>
				</view>
			</view>
			<view class="list-item flex-r ac">
				<text class="item-title">昵称</text>
				<input type="text" class="input" :value="nickname" @input="input" :maxlength="5" confirm-type="next" placeholder="请输入最多5个字的昵称"></input>
			</view>
			<view class="list-item flex-r ac">
				<text class="item-title">设置登录密码</text>
				<input type="password" class="input" v-model="password" confirm-type="next" placeholder="请输入登录密码"></input>
			</view>
			<view class="list-item flex-r ac">
				<text class="item-title">确认登录密码</text>
				<input type="password" class="input" v-model="password2" confirm-type="done" placeholder="请再次确认登录密码"></input>
			</view>
			<view class="submit-box">
				<button type="default" :class="{'active': canSubmit}" @tap="submitEditName">提交</button>
			</view>
		</view>
		<view class="cropper-wrap" v-if="cropperImg">
			<view class="cropper-wrap-tools">
				<view class="cropper-wraper-cancel" @click="cancelCropper">取消</view>
				<view class="cropper-wraper-confirm" @click="confirmCorpper">确定</view>
			</view>
			<image-cropper
				cutWidth="200px"
				id="image-cropper"
				:zoom="1"
				:angle="0"
				:keepRatio="true"
				:showCtrlBorder='true'
				:disableRotate='true'
				:imageCenter="true"
				:disableCtrl="true"
				fileType="jpg"
				:src="cropperImg"
				@load="cropperLoaded"
				@cropped="cropped"
			  />
		</view>
	</view>
</template>

<script>
	import ImageCropper from './components/nice-cropper/cropper.vue'
	import imMsg from "@/utils/common/message.js";
	import * as qiniu from 'qiniu-js'
	export default {
		data() {
			return {
				canLeave: false,
				
				nickname: '',
				password: '',
				password2: '',
				avatarImage: null,
				
				tempAvatar: null,
				cropperImg: null,
				croppedImg: null,
				domainUrl: null,
			}
		},
		components: {
			ImageCropper
		},
		computed: {
			user() {
				return this.$store.state.user
			},
			canSubmit() {
				if(this.avatarImage && this.nickname != '' && this.password != ''){
					if(this.nickname.length >= 2 && this.nickname.length <= 5 && this.password.length > 7 &&this.password == this.password2){
						return true
					}
				}
				return false
			}
		},
		onLoad() {
			//回跳地址
			this.redirectTo = this.$CHS.getRedirectTo()
			if(!this.user.is_perfect){
				this.canLeave = true
				this.$Router.replaceAll({name: 'index'})
			}
		},
		beforeRouteLeave(to, from, next) {
			if(this.canLeave){
				next();
			}else{
				next(false);
			}
		},
		methods: {
			//用户选择上传图片
			chooseImage(){
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					extension: ['jpg','png'],
					success: (res) => {
						console.log(res.tempFilePaths[0]);
						this.cropperImg = res.tempFilePaths[0];
					}
				});
			},
			//图片加载完成触发
			cropperLoaded(image){
				console.log(image);
				this.croppedImg = image.path
			},
			//每次操作裁剪触发
			cropped(imagePath, imageInfo) {
				console.log(imageInfo);
				this.croppedImg = imagePath
			},
			//取消裁剪
			cancelCropper(){
				this.cropperImg = ''
				this.croppedImg = ''
			},
			//确认完成裁剪
			confirmCorpper(){
				this.cropperImg = ''
				this.tempAvatar = this.croppedImg
				this.croppedImg = ''
				this.$ShowLoading({show: true})
				this.uploadAvatar()
			},
			//上传图片
			uploadAvatar(){
				this.$http.post({
					url: '/api/getToken',
				}).then(data => {
					console.log(data);
					if(data.success && data.result){
						this.domainUrl = data.result.url
						this.token = data.result.token
						let file = this.base64ConvertFile(this.tempAvatar)
						//七牛上传请求
						this.qiniuUpload(file).then((res)=>{
							console.log(res);
							this.avatarImage = this.domainUrl + '/' + res.key
						}).catch((err)=>{
							console.log(err);
							uni.showToast({
								title: '头像上传失败，请重试',
								icon: 'none'
							})
						}).finally(()=>{
							this.$ShowLoading({show: false})
						})
					}else{
						this.$ShowLoading({show: false})
						uni.showToast({
							title: data.message || '头像上传失败，请重试',
							icon: 'none'
						})
					}
				}).catch((err) => {
					console.log(err);
					this.$ShowLoading({show: false})
					uni.showToast({
						title: '头像上传失败，请重试',
						icon: 'none'
					})
				})
			},
			//计算输入字数
			input(e) {
				let nickname = e.detail.value.trim()
				this.$nextTick(()=>{
					this.nickname = nickname
				})
			},
			//提交修改昵称
			submitEditName(){
				if(!this.avatarImage){
					this.$ShowToast({text: '请上传头像', type: 2})
					return
				}
				if(this.nickname){
					if(this.nickname.length < 2 || this.nickname.length > 5){
						uni.showToast({
							title: '请输入2-5位长度的昵称',
							icon: 'none'
						});
						return
					}
				}else{
					this.$ShowToast({text: '昵称不能为空', type: 2})
					return
				}
				if(this.password == ''){
					this.$ShowToast({text: '密码不能为空', type: 2})
					return
				}
				if(!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\.\#\@\&\_\-\$\%\*]{8,}$/.test(this.password)){
					uni.showToast({
						title: '请输入至少8位由数字、大小写字母和特殊符号组成的密码',
						icon: 'none'
					});
					return
				}
				if(this.password != this.password2){
					uni.showToast({
						title: '两次输入的密码不一致',
						icon: 'none'
					});
					return
				}
				
				let userInfoModel = {
					nickname: this.nickname,
					avatar: this.avatarImage,
					password: this.password
				}
				this.editUserInfo(userInfoModel)
			},
			//修改用户基础信息
			editUserInfo(userInfoModel) {
				this.$http.post({
					url: '/api/appUser/perfectAppUserInfo',
					data: {
						userId: this.user.userId,
						...userInfoModel
					}
				}).then(data => {
					console.log(data);
					if(data.success){
						//请求用户最新信息
						this.$store.commit('UPDATE_USERINFO', {
							avatar: this.avatarImage,
							nickname: this.nickname,
							is_perfect: false
						});
						//信息提示
						this.$ShowToast({text: '个人信息已完善', type: 1})
						this.canLeave = true
						setTimeout(()=>{
							//返回首页
							if(this.redirectTo){
								this.$Router.replaceAll(this.redirectTo)
							}else{
								this.$Router.replaceAll({name: 'index'})
							}
						}, 500);
						setTimeout(()=>{
							//更新IM用户资料
							if(this.$store.state.imReady){
								imMsg.updateMyProfile()
							}
						}, 1500);
						
					}else{
						console.log(data);
						uni.showToast({
							title: data.message || '信息完善失败，请重试',
							icon: 'none'
						})
					}
				}).catch((err) => {
					console.log(err);
					uni.showToast({
						title: '请求错误，请稍后重试',
						icon: 'none'
					})
				})
			},
			base64ConvertFile(urlData) { // 64转file
				var arr = urlData.split(',')
				var type = arr[0].match(/:(.*?);/)[1]
				var fileExt = type.split('/')[1]
				var bstr = atob(arr[1])
				var n = bstr.length
				var u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], Date.now() + 'H5.' + fileExt, {
					type: type
				});
			},
			//七牛上传图片
			qiniuUpload(file) {
				return new Promise((resolve,reject)=>{
					let type = file.type.substr(6)
					let key = Date.now() + 'H5.' + type
					const observer = {
						next(res){
							console.log(res);
						},
						error(err){
							console.log(err);
							reject(err)
						},
						complete(res){
							console.log(res);
							resolve(res)
						}
					}
					const options = {
						quality: 0.4,
						noCompressIfLarger: true
					}
					//压缩图片
					qiniu.compressImage(file, options).then(data => {
						const observable = qiniu.upload(data.dist, key, this.token)
						const subscription = observable.subscribe(observer) // 上传开始
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	.container{
		padding: 0;
		min-height: var(--safe-height);
		background-color: #FFFFFF;
	}
	.head{
		max-width: $max-width;
		width: 100%;
		height: 450rpx;
		//background: linear-gradient(0deg, #508AFF 0%, #0055FF 99%);
		background-color: #0055FF;
		justify-content: space-between;
		position: relative;
		/* background-image: url("~@/public/images/user/wsxx.png");
		background-repeat: no-repeat;
		background-size: 100%;
		background-position: 0 -40rpx; */
		.head-info{
			color: #FFFFFF;
			margin-top: 160rpx;
			margin-left: 30rpx;
			.title{
				font-size: 42rpx;
				font-weight: 800;
				line-height: 42rpx;
			}
			.info{
				margin-top: 30rpx;
				font-size: 24rpx;
				line-height: 24rpx;
			}
			z-index: 2;
		}
		image{
			margin-top: 20rpx;
			margin-right: 10rpx;
			width: 340rpx;
			height: 360rpx;
			position: absolute;
			right: 0;
			z-index: 1;
		}
	}
	.body{
		margin-top: 20rpx;
		.list-item{
			min-height: 96rpx;
			padding: 12rpx 20rpx;
			box-sizing: border-box;
			.item-title{
				font-size: 30rpx;
				margin-right: 20rpx;
			}
			.item-right{
				flex: 2;
				justify-content: flex-end;
				.avatar{
					width: 96rpx;
					height: 96rpx;
					border-radius: 50%;
					background-color: #FFFFFF;
					background-size: 100%;
					margin-right: 10rpx;
				}
			}
			.input{
				flex: 2;
				text-align: right;
				font-size: 28rpx;
				/deep/ .uni-input-placeholder{
					color: #B3B3B3;
				}
			}
		}
		.submit-box{
			padding: 0 20rpx;
		}
	}
	.cropper-wrap {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: var(--safe-height);
		z-index: 6;
		background-color: rgba(0, 0, 0, 1);
		.cropper-wrap-tools {
			position: absolute;
			left: 0;
			top: 156rpx;
			width: 100%;
			display: flex;
			justify-content: space-between;
			z-index: 66;
			.cropper-wraper-cancel , .cropper-wraper-confirm {
				width: 250rpx;
				height: 88rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #FFFFFF;
				font-size: 32rpx;
			}
		}
	}
</style>
